from django.views.generic import View
from libs import json_response, JsonParser, Argument
from apps.message.models import MessageService, MessagePush, MessageTemplate, MessageUser
from apps.account.models import Role
from libs import human_datetime, AttrDict, wxwork
from jinja2 import Template
from datetime import datetime
import re


# Create your views here.
class MessageServiceView(View):
    def get(self, request):
        id = request.GET.get('id')
        if id:
            if not request.user.has_host_perm(id):
                return json_response(error='无权访问该主机，请联系管理员')
            return json_response(MessageService.objects.get(pk=id))
        message_services = MessageService.objects.filter(deleted_by_id__isnull=True)

        return json_response(message_services)

    def post(self, request):
        form, error = JsonParser(
            Argument('id', type=int, required=False),
            Argument('webhook', help='请输入消息服务webhook'),
            Argument('name', help='请输入消息服务名称'),
            Argument('type', handler=str.strip, help='请选择消息服务类型'),
            Argument('desc', required=False),
        ).parse(request.body)

        if error is None:
            if form.id:
                # 如果传的参数带id,则更新IDC
                MessageService.objects.filter(pk=form.pop('id')).update(**form)
            elif MessageService.objects.filter(name=form.name, deleted_by_id__isnull=True).exists():
                # MessageService名称唯一，如果已存在相同的MessageService名称则报错
                return json_response(error=f'已存在的消息服务名称【{form.name}】')
            else:
                # 新建Register记录
                message_service = MessageService.objects.create(created_by=request.user, **form)
                if request.user.role:
                    request.user.role.add_host_perm(message_service.id)
        return json_response(error=error)

    def delete(self, request):
        form, error = JsonParser(
            Argument('id', type=int, help='请指定操作对象')
        ).parse(request.GET)
        if error is None:
            role = Role.objects.filter(host_perms__regex=fr'[^0-9]{form.id}[^0-9]').first()
            application = MessageService.objects.filter(messageservice_id=form.id, deleted_by_id__isnull=True).first()
            if role:
                return json_response(error=f'角色【{role.name}】的主机权限关联了该主机，请解除关联后再尝试删除该主机')
            if application:
                return json_response(error=f'APP【{application.name}】关联了该注册中心，请解除关联后再尝试删除该注册中心')
            MessageService.objects.filter(pk=form.id).update(
                deleted_at=human_datetime(),
                deleted_by=request.user,
            )
        return json_response(error=error)


class MessagePushView(View):
    def get(self, request):
        id = request.GET.get('id')
        if id:
            if not request.user.has_host_perm(id):
                return json_response(error='无权访问该主机，请联系管理员')
            return json_response(MessagePush.objects.get(pk=id))
        message_push = MessagePush.objects.filter()
        perms = [x.id for x in message_push]
        message_service = MessageService.objects.filter(deleted_by_id__isnull=True)
        message_user = MessageUser.objects.filter(deleted_by_id__isnull=True)

        return json_response({
            'message_push': [x.to_dict() for x in message_push],
            'perms': perms,
            'message_service': [x.to_dict() for x in message_service],
            'message_user': [x.to_dict() for x in message_user]
        })

    def post(self, request):
        form, error = JsonParser(
            Argument('checked', required=False),
        ).parse(request.body)
        template_required = form.checked
        print(template_required)
        if template_required == 'True':
            template_required = True
        elif template_required == 'False':
            template_required = False
        else:
            return json_response(error=f'未知错误')

        form, error = JsonParser(
            Argument('id', type=int, required=False),
            Argument('messageservice_id', help='请选择消息服务'),
            Argument('mentioned_list', help='@人员列表', required=False),
            Argument('content', help='请输入消息内容'),
            Argument('template', help='请选择消息模板', required=template_required),
            Argument('desc', required=False),
        ).parse(request.body)
        print(form)
        if error is None:
            user_ids = eval(form.mentioned_list)
            message_service = MessageService.objects.filter(pk=form.messageservice_id).first()
            webhook = message_service.webhook
            if template_required:
                current_time = datetime.now().strftime('%Y年%m月%d日 %H时%M分')
                jinja_template = Template(form.template)
                render = jinja_template.render(userids=user_ids, datetime=current_time, content=form.content)
                render = re.sub('[\n]+', '\n', render)
                render = re.sub('>\n<', '> <', render)
                alert = wxwork.WxWorkAlerter(content=render, webhook=webhook)
            else:
                render = form.content
                alert = wxwork.WxWorkAlerter(content=render, mentioned_list=user_ids, webhook=webhook)
            alert.alert()
            if form.id:
                pass
            else:
                # 创建
                message_push = MessagePush.objects.create(created_by=request.user, **form)
                if request.user.role:
                    request.user.role.add_host_perm(message_push.id)
        return json_response(error=error)

    def delete(self, request):
        form, error = JsonParser(
            Argument('id', type=int, help='请指定操作对象')
        ).parse(request.GET)
        if error is None:
            role = Role.objects.filter(host_perms__regex=fr'[^0-9]{form.id}[^0-9]').first()
            if role:
                return json_response(error=f'角色【{role.name}】的主机权限关联了该用户，请解除关联后再尝试删除该VPN用户')

            vpnuser_queryset = VpnUser.objects.filter(pk=form.id)
            vpnuser_queryset.update(deleted_at=human_datetime(), deleted_by=request.user,)
            vpnuser = vpnuser_queryset.first()
            vpnserver = VpnServer.objects.filter(pk=vpnuser.vpnserver_id).first()
            if vpnserver.type in ('huaweicloud', 'fastapi'):
                return json_response(error=f"此类型VPN服务暂不支持在线删除用户。")
            client = get_vpn_client(vpnserver)
            res = client.userdel(vpnuser.name)

        return json_response(error=error)

    def options(self, request):
        form, error = JsonParser(
            Argument('id', type=int, help='请指定操作对象'),
            Argument('status', type=int, help='请指定操作对象')
        ).parse(request.GET)
        if error is None:
            application = Application.objects.filter(pk=form.id).first()
            application.status = APPLICATION_STATUS[form.status]
            register = Register.objects.filter(pk=application.register_id).first()
            client = get_register_client(register)
            if client:
                ipaddress, port = application.socket.split(':')
                app = client.get_app(ipaddress, port)
                client.change_app_status(app, form.status)
                application.save()

        return json_response(error=error)


class MessageTemplateView(View):
    def get(self, request):
        templates = MessageTemplate.objects.all()
        types = [x['type'] for x in templates.order_by('type').values('type').distinct()]
        return json_response({'types': types, 'templates': [x.to_dict() for x in templates]})

    def post(self, request):
        form, error = JsonParser(
            Argument('id', type=int, required=False),
            Argument('name', help='请输入模版名称'),
            Argument('type', help='请选择模版类型'),
            Argument('body', help='请输入模版内容'),
            Argument('desc', required=False)
        ).parse(request.body)
        if error is None:
            if form.id:
                form.updated_at = human_datetime()
                form.updated_by = request.user
                MessageTemplate.objects.filter(pk=form.pop('id')).update(**form)
            else:
                form.created_by = request.user
                MessageTemplate.objects.create(**form)
        return json_response(error=error)

    def delete(self, request):
        form, error = JsonParser(
            Argument('id', type=int, help='请指定操作对象')
        ).parse(request.GET)
        if error is None:
            MessageTemplate.objects.filter(pk=form.id).delete()
        return json_response(error=error)
